package com.example.repository.write.datatypes;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class PhoneTypeHandler extends BaseTypeHandler<PhoneNumber>
{
    private ObjectMapper _objectMapper = new ObjectMapper();

    public PhoneTypeHandler(){
        System.out.println("PhoneTypeHandler");
    }
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, PhoneNumber parameter, JdbcType jdbcType) throws SQLException
    {
        try{
            if(parameter ==null)
                ps.setNString(i, null);
            else
                ps.setNString(i, _objectMapper.writeValueAsString(parameter));
        }catch (JsonProcessingException e){
            throw new SQLException("serialize phonenumber error", e);
        }
    }

    @Override
    public PhoneNumber getNullableResult(ResultSet rs, String columnName) throws SQLException
    {
        String str = rs.getNString(columnName);
        if(str == null || str.isEmpty()){
            return null;
        }
        try{
            return _objectMapper.readValue(str, PhoneNumber.class);
        }catch (IOException e){
            throw new SQLException("derialize phonenumber error", e);
        }
    }

    @Override
    public PhoneNumber getNullableResult(ResultSet rs, int columnIndex) throws SQLException
    {
        String str = rs.getNString(columnIndex);
        if(str == null || str.isEmpty()){
            return null;
        }
        try{
            return _objectMapper.readValue(str, PhoneNumber.class);
        }catch (IOException e){
            throw new SQLException("derialize phonenumber error", e);
        }
    }

    @Override
    public PhoneNumber getNullableResult(CallableStatement cs, int columnIndex) throws SQLException
    {
        String str = cs.getNString(columnIndex);
        if(str == null || str.isEmpty()){
            return null;
        }
        try{
            return _objectMapper.readValue(str, PhoneNumber.class);
        }catch (IOException e){
            throw new SQLException("derialize phonenumber error", e);
        }
    }
}
